//
//  MyBankCardController.m
//  Experss
//
//  Created by 嗯，大葱 on 17/8/8.
//  Copyright © 2017年 嗯，大葱. All rights reserved.
//

#import "MyBankCardController.h"
#import "RemoBankCardViewController.h"
#import "MyBankCardCell.h"
#import "AddBankCardVController.h"
#import "BankCardModel.h"



@interface MyBankCardController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong)UIButton *rightBtn2;//右侧按钮

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *dataArray;
@end

@implementation MyBankCardController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    [self getBankList];//获取银行卡列表
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _dataArray = [NSMutableArray array];
    [self configureNaBar];
    
    [self configureView];
    


}


- (void)configureNaBar {
    self.navigationItem.title = @"我的银行卡";
    //设置导航栏按钮的边距
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame= CGRectMake(0, 0, 60, 30);
    [rightBtn setImage:[UIImage imageNamed:@"all_fanhui2"] forState:(UIControlStateNormal)];
    [rightBtn addTarget:self action:@selector(handleBackAxtion) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    UIBarButtonItem *negativeSpacerleft = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    /**
     width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和  边界间距为5pix，所以width设为-5时，间距正好调整为0；width为正数 时，正好相反，相当于往左移动width数值个像素
     */
    negativeSpacerleft.width = -20;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacerleft, btn_left, nil];
    
    
    //设置导航栏按钮的边距
    _rightBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightBtn2.frame= CGRectMake(0, 0, 60, 30);
    [_rightBtn2 setTitle:@"解绑" forState:(UIControlStateNormal)];
    [_rightBtn2 addTarget:self action:@selector(onClickRight2) forControlEvents:UIControlEventTouchUpInside];
    _rightBtn2.titleLabel.font = kFont16;
    [_rightBtn2 setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    UIBarButtonItem *btn_right = [[UIBarButtonItem alloc] initWithCustomView:_rightBtn2];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    negativeSpacer.width = -20;
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_right, nil];
    
}

- (void)handleBackAxtion {
    [self.navigationController popViewControllerAnimated:YES];
}


//配置视图控制器
- (void)configureView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreen_Width, kScreen_Height -64 - 54- 5) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = kSpNone;
    [self.view addSubview:_tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"MyBankCardCell" bundle:nil] forCellReuseIdentifier:@"MyBankCardCell"];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 150;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyBankCardCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyBankCardCell"];
    //hong  lan lv
    
    BankCardModel *model = self.dataArray[indexPath.row];
    cell.selectionStyle = kSeNone;
    if ([model.bankname isEqualToString:@"中国农业银行"]) {
        cell.bgImage.image = [UIImage imageNamed:@"lv"];
              cell.logImage.image = [UIImage imageNamed:@"nongxin"];
    }
    else if([model.bankname isEqualToString:@"中国工商银行"]) {
        cell.bgImage.image = [UIImage imageNamed:@"hong"];
        cell.logImage.image = [UIImage imageNamed:@"zhaohang"];
    }else {
        cell.bgImage.image = [UIImage imageNamed:@"lan"];
        cell.logImage.image = [UIImage imageNamed:@"yinlian"];
    }
    cell.cardNumLB.text = [self getNewBankNumWitOldBankNum:model.cardnum];
    cell.titleLB.text = model.bankname;
    
    
    
    
    return cell
    ;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([_typeST isEqualToString:@"tiXian"]) {
        BankCardModel *model = self.dataArray[indexPath.row];
        NSDictionary *dict = @{@"BankCard":model};
        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeBankTiXain" object:nil userInfo:dict];
        [self.navigationController popViewControllerAnimated:YES];

        
        
        
    }else {
        
        return;
    }
    
}


-(NSString *)getNewBankNumWitOldBankNum:(NSString *)bankNum
{
    NSMutableString *mutableStr;
    if (bankNum.length) {
        mutableStr = [NSMutableString stringWithString:bankNum];
        for (int i = 0 ; i < mutableStr.length; i ++) {
            if (i>2&&i<mutableStr.length - 3) {
                [mutableStr replaceCharactersInRange:NSMakeRange(i, 1) withString:@"*"];
            }
        }
        NSString *text = mutableStr;
        NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
        text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
        NSString *newString = @"";
        while (text.length > 0) {
            NSString *subString = [text substringToIndex:MIN(text.length, 4)];
            newString = [newString stringByAppendingString:subString];
            if (subString.length == 4) {
                newString = [newString stringByAppendingString:@" "];
            }
            text = [text substringFromIndex:MIN(text.length, 4)];
        }
        newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
        return newString;
    }
    return bankNum;
    
}


#pragma mark 跳转到解绑银行卡界面
- (void)onClickRight2 {
    if (_dataArray.count == 0) {
        [MBProgressHUD showText:@"暂无可解绑的银行卡"];
        return;
    }
    RemoBankCardViewController *pass = [[RemoBankCardViewController alloc] init];
    
    pass.cardListArray = [NSArray arrayWithArray:_dataArray];
    [self.navigationController pushViewController:pass animated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//添加银行卡按钮的点击事件
- (IBAction)addBankCardAction:(UIButton *)sender {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    //取值
    NSString *username = [defaults objectForKey:@"isPayPassWord"];
    if ([[NSString stringWithFormat:@"%@",username] isEqualToString:@"0"]) {
        [MBProgressHUD showText:@"请先去个人资料设置支付密码"];
        return;
    }
    
    
    
    AddBankCardVController *pass = [[AddBankCardVController alloc] init];
    
    [self.navigationController pushViewController:pass animated:YES];
    
    
    
}
#pragma mark   －＝ －＝－＝ －＝－ －＝ －＝ －＝获取银行卡列表
//获取银行卡列表
- (void)getBankList {
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    [HttpRequest getWithURLString:POST(Shop_PersonalGetBankCardList) parameters:parameDic success:^(id responseObject) {
        if ([responseObject[@"ret"] intValue] != 200) {
            [MBProgressHUD showText:@"获取银行卡出错"];
            return ;
        }
        if (![[NSString stringWithFormat:@"%@",responseObject[@"data"][@"code"]] isEqualToString:@"0"]) {
            [MBProgressHUD showText:responseObject[@"data"][@"msg"]];
            return;
        }
        NSArray *cardList = [[responseObject objectForKey:@"data"]objectForKey:@"list"];
        self.dataArray =[BankCardModel mj_objectArrayWithKeyValuesArray:cardList];

        
        [self.tableView reloadData];
        if (self.dataArray.count == 0) {
            self.tableView.hidden = YES;
            if (_imageV) {
                [_imageV removeFromSuperview];
            }
            if (_twoLabel) {
                [_twoLabel removeFromSuperview];
            }
            
            
            _imageV = [[UIImageView alloc] init];
            _imageV.frame = CGRectMake(kScreen_Width/2-75, 200, 150, 150);
            _imageV.image = [UIImage imageNamed:@"zanwudizhi"];
            [self.view addSubview:_imageV];
            [self.tableView.mj_footer endRefreshing];
            _twoLabel = [[UILabel alloc] initWithFrame:CGRectMake(kScreen_Width/2-100, CGRectGetMaxY(_imageV.frame)+20, 200, 30)];
            _twoLabel.text = @"暂没有可用的银行卡哦";
            _twoLabel.textColor = [UIColor grayColor];
            _twoLabel.font = kFont14;
            _twoLabel.textAlignment = NSTextAlignmentCenter;
            [self.view addSubview:_twoLabel];
            
        }
        else {
            self.tableView.hidden = NO;
            [_imageV removeFromSuperview];
            [_twoLabel removeFromSuperview];
            
        }
        
    } failure:^(NSError *error) {
        
    }];
    
}


@end
